<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" @click="handleAdd"
          >新增</el-button
        >
        <!-- v-hasPermi="['workflow:category:add']" -->
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-edit"
          :disabled="single"
          @click="handleUpdate"
          >修改</el-button
        >
        <!-- v-hasPermi="['workflow:category:edit']" -->
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-delete"
          :disabled="single"
          @click="handleDelete"
          >删除</el-button
        >
        <!-- v-hasPermi="['workflow:category:remove']" -->
      </el-col>
      <!-- <right-toolbar
        v-model:showSearch="showSearch"
        @queryTable="getList"
      ></right-toolbar> -->
    </el-row>

    <el-table
      v-loading="loading"
      :data="postList"
      @selection-change="handleSelectionChange"
      border
    >
      <el-table-column type="selection" width="55" />
      <el-table-column label="所属单位" prop="orgName" width="150" />
      <el-table-column label="岗位名称" prop="postName" width="180" />
      <el-table-column label="审核人" prop="userName" />
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />
    <SelectDialog
      :dialog-param="Notifyingdialog"
      @ok="selectNotifying"
      @close="Notifyingdialog.isDialog = false"
    />
    <!-- 添加或修改【请填写功能名称】对话框 -->
    <el-dialog
      :title="title"
      v-model="open"
      width="500px"
      append-to-body
      destroy-on-close
      class="uniquedialog"
    >
      <el-form ref="form" :model="formModel" :rules="rules" label-width="80px">
        <el-form-item label="所属单位" prop="orgId">
          <el-tree-select
            style="width: 100%"
            v-model="formModel.orgId"
            :data="companyOptions"
            :props="{
              value: 'id',
              label: 'label',
              children: 'children'
            }"
            placeholder="请选择所属单位"
            value-key="id"
            filterable
            @change="changeOrg"
            check-on-click-node
            show-checkbox
            check-strictly
            class="uniquecustomNodeClass"
          />
        </el-form-item>
        <el-form-item label="岗位名称" prop="postName">
          <el-input v-model="formModel.postName" placeholder="请输入岗位名称" />
        </el-form-item>
        <el-form-item label="审核人" prop="userId">
          <el-select
            clearable
            v-model="formModel.userId"
            placeholder="请选择审核人"
            @focus="userInputFocusInit"
            class="w-full"
            multiple
            @clear="changeUser"
            @remove-tag="deleteTag"
          >
            <el-option
              v-for="(item, index) in selectObjForm['UUid']"
              :key="index"
              :label="selectObjForm['name'][index]"
              :value="item"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div class="footer text-right">
        <el-button @click="cancel">取 消</el-button>
        <el-button :loading="buttonLoading" type="primary" @click="submitForm"
          >确 定</el-button
        >
      </div>
    </el-dialog>
  </div>
</template>

<script setup name="WorkPost">
import {
  addWfpost,
  delWfpost,
  updateWfpost,
  listWfpost
} from '@/api/workflow/post'
import { reactive, toRefs } from 'vue'
import useCommonStore from '@/store/modules/common'
const commonStore = useCommonStore()
const { proxy } = getCurrentInstance()
const data = reactive({
  // 按钮loading
  buttonLoading: false,
  // 遮罩层
  loading: true,
  // 选中数组
  ids: [],
  // 非单个禁用
  single: true,
  // 非多个禁用
  multiple: true,
  // 总条数
  total: 0,
  // 表格数据
  postList: [],
  // 弹出层标题
  title: '',
  // 是否显示弹出层
  open: false,
  // 查询参数
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    orgId: null,
    postName: null,
    userId: null
  },
  // 表单参数
  formModel: {
    orgId: null,
    postName: null,
    userId: null,
    orgName: null,
    userName: null,
    id: null
  },
  // 表单校验
  rules: {
    orgId: [{ required: true, message: '所属单位不能为空', trigger: 'blur' }],
    postName: [{ required: true, message: '岗位名称不能为空', trigger: 'blur' }]
    // userId: [{ required: true, message: '审核人不能为空', trigger: 'blur' }]
  },
  Notifyingdialog: {},
  selectObjForm: {
    UUid: [],
    name: []
  }
})
const {
  buttonLoading,
  loading,
  ids,
  single,
  multiple,
  total,
  postList,
  title,
  open,
  queryParams,
  formModel,
  rules,
  Notifyingdialog,
  selectObjForm
} = toRefs(data)
/** 查询列表 */
function getList() {
  loading.value = true
  if (
    Array.isArray(queryParams.value.userId) &&
    queryParams.value.userId.length
  ) {
    queryParams.value.userId = queryParams.value.userId
      .toString()
      .replace(/U/g, '')
  } else {
    queryParams.value.userId = null
  }
  listWfpost(queryParams.value).then(response => {
    postList.value = response.rows
    total.value = response.total
    loading.value = false
  })
}
// 取消按钮
function cancel() {
  open.value = false
  reset()
}
// 表单重置
function reset() {
  formModel.value = {
    orgId: null,
    postName: null,
    userId: null,
    orgName: null,
    userName: null
  }
}
// 选中行数据
const selectRow = ref([])
// 多选框选中数据
function handleSelectionChange(selection) {
  selectRow.value = selection
  ids.value = selection.map(item => item.id)
  single.value = selection.length !== 1
  //   multiple.value = !selection.length
}
/** 新增按钮操作 */
function handleAdd() {
  reset()
  open.value = true
  title.value = '添加流程岗位'
}
/** 修改按钮操作 */
function handleUpdate() {
  loading.value = true
  reset()
  loading.value = false
  formModel.value = {
    orgId: selectRow.value[0].orgId,
    orgName: selectRow.value[0].orgName,
    postName: selectRow.value[0].postName,
    userId: selectRow.value[0].userId
      ? selectRow.value[0].userId.split(',').map(v => 'U' + v)
      : '',
    userName: selectRow.value[0].userName,
    id: selectRow.value[0].id
  }
  selectObjForm.value['UUid'] = selectRow.value[0].userId
    ? selectRow.value[0].userId.split(',').map(v => 'U' + v)
    : []
  selectObjForm.value['name'] = selectRow.value[0].userName
    ? selectRow.value[0].userName.split(',')
    : ''
  open.value = true
  title.value = '修改流程岗位'
}
/** 提交按钮 */
function submitForm() {
  proxy.$refs['form'].validate(valid => {
    if (valid) {
      buttonLoading.value = true
      if (
        Array.isArray(formModel.value.userId) &&
        formModel.value.userId.length
      ) {
        formModel.value.userId = formModel.value.userId
          .toString()
          .replace(/U/g, '')
      } else {
        formModel.value.userId = null
      }
      if (title.value === '修改流程岗位') {
        updateWfpost(formModel.value)
          .then(response => {
            proxy.$modal.msgSuccess('修改成功')
            open.value = false
            getList()
          })
          .finally(() => {
            buttonLoading.value = false
          })
      } else {
        addWfpost(formModel.value)
          .then(response => {
            proxy.$modal.msgSuccess('新增成功')
            open.value = false
            getList()
          })
          .finally(() => {
            buttonLoading.value = false
          })
      }
    }
  })
}
/** 删除按钮操作 */
function handleDelete() {
  const categoryIds = ids.value
  proxy.$modal
    .confirm('是否确认删除该数据项？')
    .then(() => {
      loading.value = true
      return delWfpost(categoryIds)
    })
    .then(() => {
      loading.value = false
      getList()
      proxy.$modal.msgSuccess('删除成功')
    })
    .finally(() => {
      loading.value = false
    })
}

const companyOptions = ref([])
async function getCompany() {
  // 所属单位列表
  commonStore.getCompanyData().then(data => {
    companyOptions.value = data
  })
}

async function userInputFocusInit() {
  const obj = {
    nodeKey: 'uuid',
    dataType: 'person',
    apiParams: {},
    multiple: true,
    checkStrictly: false,
    title: '人员选择',
    defaultCheckedKeys: [],
    isDialog: true
  }

  obj.defaultCheckedKeys = Array.isArray(formModel.value.userId)
    ? formModel.value.userId
    : formModel.value.userId
    ? formModel.value.userId.split(',').map(v => 'U' + v)
    : []

  Notifyingdialog.value = obj
}

// selectDialog 组件确定事件
function selectNotifying(val) {
  console.log(val, '123')
  selectObjForm.value['UUid'] = val.defaultCheckedKeys
    ? val.defaultCheckedKeys.map(v => v.replace('U', ''))
    : []
  selectObjForm.value['name'] = val.labelData
  formModel.value.userName = val.labelData.toString()
  formModel.value.userId = val.defaultCheckedKeys
    ? val.defaultCheckedKeys.map(v => v.replace('U', ''))
    : null
  if (formModel.value.userId === null) {
    formModel.value.userName = null
  }

  Notifyingdialog.value.isDialog = false
}
// 新增/修改 所属单位改变
function changeOrg(val) {
  const list = [companyOptions.value[0], ...companyOptions.value[0].children]
  const name = list.filter(v => v.id === val)[0].label
  formModel.value.orgName = name ? name : null
}

// 删除审核人员
function changeUser(val) {
  formModel.value.userName = null
}

// 删除select--tag
function deleteTag(val) {
  const index = selectObjForm.value.UUid.indexOf(val)
  formModel.value.userName = formModel.value.userName.split(',')
  formModel.value.userName.splice(index, 1)
  formModel.value.userName = formModel.value.userName.toString()
  selectObjForm.value.UUid.splice(index, 1)
  selectObjForm.value.name.splice(index, 1)
}
getCompany()
getList()
</script>

<style lang="scss">
.uniquecustomNodeClass .el-checkbox__inner {
  border-radius: 50% !important;
}
</style>
